package huanzhao.erp.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import huanzhao.erp.domain.entity.Team;
import huanzhao.erp.domain.enumerate.error.ProcessError;
import huanzhao.erp.domain.enumerate.error.ValidationError;
import huanzhao.erp.domain.po.Result;
import huanzhao.erp.domain.types.OperationTarget;
import huanzhao.erp.domain.types.OperationType;
import huanzhao.erp.domain.vo.TeamVO;
import huanzhao.erp.mapper.PositionMapper;
import huanzhao.erp.mapper.StaffMapper;
import huanzhao.erp.mapper.TaskMapper;
import huanzhao.erp.mapper.TeamMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author April
 * 2024/10/2 17:30
 * @version 1.0
 */
@Service
public class TeamService extends ServiceImpl<TeamMapper, Team> {
    private final TeamMapper teamMapper;
    private final StaffMapper staffMapper;
    private final ConvertService convertService;
    private final BasicService basicService;
    private final TaskMapper taskMapper;
    private final PositionMapper positionMapper;

    public TeamService(TeamMapper teamMapper, StaffMapper staffMapper, ConvertService convertService, BasicService basicService, TaskMapper taskMapper, PositionMapper positionMapper) {
        this.teamMapper = teamMapper;
        this.staffMapper = staffMapper;
        this.convertService = convertService;
        this.basicService = basicService;
        this.taskMapper = taskMapper;
        this.positionMapper = positionMapper;
    }

    /**
     * 获取所有团队
     *
     * @return List<Team>
     * 2024/6/12 下午8:47:19
     */
    public List<TeamVO> getAllTeams() {
        List<Team> teams = teamMapper.getAllTeams();
        if (teams == null) {
            return Collections.emptyList();
        }
        List<TeamVO> result = new ArrayList<>();
        teams.forEach(team -> result.add(convertService.convertTeam(team)));
        return result;
    }


    /**
     * 检查团队信息是否正确
     *
     * @param team 团队信息
     * @return Result<?>
     * 2024/6/12 下午8:56:15
     */
    public Result<?> checkTeamInfo(Team team) {
        if (team == null) {
            return Result.error(ValidationError.VALIDATION_ERROR, "团队信息为空");
        }
        if (StringUtils.isBlank(team.getName())) {
            return Result.error(ValidationError.VALIDATION_ERROR, "团队名称为空");
        }
        if (team.getName().length() > 50) {
            return Result.error(ValidationError.VALIDATION_ERROR, "团队名称过长");
        }
        Long managerId = team.getManagerId();
        if (managerId == null || managerId <= 0) {
            return Result.error(ValidationError.VALIDATION_ERROR, "团队管理员id为空");
        }

        if (!staffMapper.exist(managerId)) {
            return Result.error(ValidationError.VALIDATION_ERROR, "团队管理员不存在");
        }
        return Result.ok("团队信息正确");
    }


    /**
     * 根据团队名获取团队
     *
     * @param name 团队名
     * @return Team
     * 2024/6/12 下午9:10:15
     */
    public Team getTeamByName(String name) {
        return teamMapper.getTeamByName(name);
    }

    /**
     * 添加团队
     *
     * @param team 团队信息
     * @return Result<?>
     * 2024/6/12 下午9:11:28
     */
    public Result<?> addTeam(Team team) {
        try {
            save(team);
            return Result.ok("添加团队成功");
        } catch (Exception e) {
            log.error("添加团队失败", e);
            return Result.error("其他错误，请联系开发人员处理");
        }
    }

    /**
     * 修改团队
     *
     * @param team 团队信息
     * @return Result<?>
     * 2024/6/12 下午9:18:25
     */
    public Result<?> updateTeam(Team team) {
        try {
            updateById(team);
            return Result.ok("修改团队成功");
        } catch (Exception e) {
            log.error("修改团队失败", e);
            return Result.error("其他错误，请联系开发人员处理");
        }
    }

    /**
     * 获取团队中的员工数量
     *
     * @param teamId 团队id
     * @return int
     * 2024/6/12 下午9:45:49
     */
    public int getTeamStaffNum(Long teamId) {
        return teamMapper.getTeamStaffNum(teamId);
    }

    /**
     * 解散团队
     *
     * @param id 团队id
     * @return Result<?>
     * 2024/6/12 下午9:47:25
     */
    public Result<?> disbandTeam(Long id) {
        Team team = getById(id);
        if (team == null) {
            return Result.error(ProcessError.TEAM_NOT_FOUND, "团队不存在");
        }
        int num = getTeamStaffNum(id);
        if (num > 0) {
            return Result.error(ProcessError.TEAM_REMAIN_STAFF, "团队中还有" + num + "名员工，请先将员工移出团队");
        }
        int runningTaskNum = taskMapper.getTeamRunningTaskNum(id);
        if (runningTaskNum > 0) {
            return Result.error(ProcessError.TEAM_HOLD_TASKS, "团队中还有" + runningTaskNum + "个任务尚未完成，请等待任务完成后再解散团队");
        }
        // 删除团队
        removeById(team.getId());
        // 记录操作
        basicService.recordOps(OperationTarget.TEAM, OperationType.DELETE, team.getId());
        return Result.ok("解散团队成功");
    }


    /**
     * 获取当前员工的所有归属团队
     *
     * @return List<Team>
     * 2024/6/22 下午4:32:21
     */
    public List<TeamVO> getStaffBelongTeams() {
        List<Team> teams = teamMapper.getStaffBelongTeams(basicService.getCurrentStaffId());
        if (teams == null) {
            return Collections.emptyList();
        }
        List<TeamVO> result = new ArrayList<>();
        teams.forEach(team -> result.add(convertService.convertTeam(team)));
        return result;
    }

    /**
     * 判断团队是否不存在
     *
     * @param teamId 团队id
     * @return boolean
     * 2024/10/4 11:31:25
     */
    public boolean notExists(long teamId) {
        return !teamMapper.exists(teamId);
    }

    /**
     * 查询所有团队基本信息
     *
     * @return List<TeamVO>
     * 2024/10/4 11:33:00
     */
    public List<TeamVO> getAllTeamBasic() {
        List<TeamVO> teams = teamMapper.getAllTeamBasic();
        if (teams == null) {
            return Collections.emptyList();
        }
        return teams;
    }

}
